package com.mzj.saas.mservice.smartlock.service.xizhao;

import com.alibaba.fastjson.JSON;
import com.mzj.saas.commons.enums.XzLockEventTypeEnum;
import com.mzj.saas.mservice.lock.Repository.SmartLockAuthRepository;
import com.mzj.saas.mservice.lock.Repository.SmartLockRepository;
import com.mzj.saas.mservice.lock.entity.SmartLock;
import com.mzj.saas.mservice.lock.entity.SmartLockAuth;
import com.mzj.saas.mservice.smartlock.vo.SmartLockCallBackVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 熙照-事件回调
 *
 * @author shun
 * @createDate: 2021年7月6日 上午9:55:50
 * @version: 1.0
 */
@Service
public class SmartLockXzCallBackService {

    private static final Logger log = LoggerFactory.getLogger(SmartLockXzCallBackService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SmartLockRepository smartLockRepository;
    @Autowired
    private SmarkLockXzEventHandleService smarkLockXzEventHandleService;
    @Autowired
    private SmartLockAuthRepository smartLockAuthRepository;

    /**
     * 熙照-智能锁回调url
     *
     * @param vo
     * @return
     */
    public Map<String, Object> lockCallback(SmartLockCallBackVO vo) {
        log.info("熙照, 智能锁回调/事件url------vo={}", JSON.toJSONString(vo));
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("desc", "成功");
        result.put("code", 0);
        try {

            if (StringUtils.isBlank(vo.getEventType()) || StringUtils.isBlank(vo.getDeviceId())) {
                log.warn("参数错误");
                return result;
            }

            XzLockEventTypeEnum typeEnum = XzLockEventTypeEnum.getLockType(vo.getEventType());
            switch (typeEnum) {
                case ONLINE:// 网关/门锁在线
                    smarkLockXzEventHandleService.lockOnlineCallBack(vo);
                    break;
                case OFFLINE:// 网关/门锁离线
                    smarkLockXzEventHandleService.lockOfflineCallBack(vo);
                    break;
                case ADD_PART:// 门锁入网/注册-1
                    smarkLockXzEventHandleService.addParkCallBack(vo);
                    break;
                case DEL_PART:// 门锁退网事件
                    // 待定
                    break;
                case UN_LOCK:// 开门锁
                    smarkLockXzEventHandleService.openRecordCallBack(vo);
                    break;
                case FAC_RESET:// 门锁初始化
                    // 待定
                    break;
                case POWER:// 门锁低电量事件
                    smarkLockXzEventHandleService.lowBatteryCallBack(vo);
                    break;
                case PWD_CHANGED:// 门锁密码改变
                    smarkLockXzEventHandleService.clearPwdCallBack(vo);
                    break;
                case FREEZE_EVENT:// 门锁密码冻结/解冻
                    smarkLockXzEventHandleService.freezeOrUnfreezeCardCallBack(vo);
                    break;
                case DOOR_STATUS:// 门锁门开关状态事件
                    // 待定
                    break;
                case ADMIN_PWD_CHANGED:// 门锁管理员密码改变事件
                    // 待定
                    break;
                default:
                    log.warn("智能锁回调事件处理 = {}", typeEnum.getCallBackType());
                    break;
            }

            // 更新智能锁授权人数
            updateOauthNumber(vo);

            return result;
        } catch (Exception e) {
            log.error("智能锁回调事件异常" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 更新智能锁授权人数
     *
     * @param vo
     */
    public void updateOauthNumber(SmartLockCallBackVO vo) {
        try {
            String sn = vo.getDeviceId();
            log.warn("更新智能锁授权人数 sn={}", sn);
            SmartLock smartLock = smartLockRepository.findBySn(sn);

            if (smartLock == null) {
                log.warn("更新智能锁授权人数 sn值未找到锁 sn={}", sn);
                return;
            }
            Long lockId = smartLock.getId();
            Integer bindType = smartLock.getBindType();
            Integer bindStatus = smartLock.getBindStatus();

            int oauthNumber = 0;
            if (bindType == 1 && bindStatus == 1) {// 单位锁
                List<SmartLockAuth> auths = smartLockAuthRepository.findByLockIdAndBindType(lockId, 0);

                for (SmartLockAuth auth : auths) {
                    if (auth.getPwdStatus() == 1 || auth.getFingerprintStatus() == 1 || auth.getCardStatus() == 1
                            || auth.getCpuStatus() == 1 || auth.getBleStatus() == 1 || auth.getFaceStatus() == 1) {
                        oauthNumber = oauthNumber + 1;
                    }
                }

            } else if (bindType == 2 && bindStatus == 2) {// 个人锁
                List<SmartLockAuth> auths = smartLockAuthRepository.findByLockIdAndBindType(lockId, 1);

                for (SmartLockAuth auth : auths) {
                    if (auth.getPwdStatus() == 1 || auth.getFingerprintStatus() == 1 || auth.getCardStatus() == 1
                            || auth.getCpuStatus() == 1 || auth.getBleStatus() == 1 || auth.getFaceStatus() == 1) {
                        oauthNumber = oauthNumber + 1;
                    }
                }
            }

            smartLock.setOauthNumber(oauthNumber);
            smartLockRepository.save(smartLock);
        } catch (Exception e) {
            log.error("更新智能锁授权人数异常" + e.getMessage(), e);
        }
    }
}
